'''
Created on Sep 7, 2012

@author: petrina
'''
from link_indicator import Link_indicator
from indiutils import Indiutils
import logging


class Buffer_speed(Link_indicator):
    '''
    Calculates the buffer index for every time interval (using aggregated fcd-data).
    
    Formula for calculating the indicator: 
        bs_i = att_i - wtt_i
            where:
                - bs_i... Buffer-Speed for time interval i
                - wts ... Worst-case-travel-speed  for time interval i
                - ats ... average-travel-speed for time interval i
                
    As worst-case-speed the 5th percentile travel speed is chosen.
    
    unit: kilometers per hour (km/h)
    '''


    def __init__(self, link):
        '''        
        @param link: Link-object (containing valid records and timeseries) 
        '''
        
        Link_indicator.__init__(self, link)
        
        self._name = 'Buffer Speed'
        self._mr_name =  'buffer_speed' 
        self._unit = 'km/h' if link.records.is_kph else 'm/s'
        #self.unit.__doc__= 'kilometers per hour (hm/h)'
        
        self._create_title(link.id, link.direction)
        
        logging.debug("Buffer_speed: created new Buffer_speed")
        
    #----------------------public methods of the class-------------------------

    def calculate(self):
        '''
        @return: buffer speed for every time interval as list of Result_values
        '''
        
        logging.info("Buffer_speed: staring to calculate the buffer speed")
        
        utils = Indiutils()
        p05 = utils.p5_speed(self._link.timeseries)
        ats = utils.calc_average_of(self._link.records, "speed")
        self._values = []

        # build the buffer time for every time interval
        for i in range(self._intervals):
            # treat empty lists (= no measurement)
            value = ats[i] - p05[i] if p05[i] is not None and ats[i] is not None else None
            self._values.append(value)
        
        logging.debug("Buffer_speed: finished calculating the buffer speed")

        return self._values